package com.pj.xfxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pj.xfxh.domain.RoleContent;
import com.pj.xfxh.listener.XhWebSocketListener;
import com.pj.xfxh.project.entity.Topic;
import com.pj.xfxh.project.entity.TopicMessage;
import com.pj.xfxh.project.service.TopicMessageService;
import com.pj.xfxh.project.service.TopicService;
import com.pj.xfxh.service.XhService;
import com.pj.xfxh.utils.XhUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class XhServiceImpl implements XhService {

    @Autowired
    private TopicMessageService topicMessageService;

    @Override
    public List<TopicMessage> ask(String question, Long userId, Long topicId, Long platformId) throws Exception {

        // 获取历史对话信息
        List<RoleContent> historyList = getHistory(userId, topicId, platformId);

        // 建立WebSocket连接并获取回答内容
        String answer = getAnswer(question, historyList);

        // 将对话信息持久化到MySQL数据库
        return persistConversation(userId, topicId, platformId, question, answer);

    }

    private List<RoleContent> getHistory(Long userId, Long topicId, Long platformId) {
        return topicMessageService.getMessagesByUserId(userId, topicId, platformId);
    }

    private String getAnswer(String question, List<RoleContent> historyList) throws Exception {
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = XhUtils.getRequest();
        XhWebSocketListener listener = new XhWebSocketListener(historyList);
        client.newWebSocket(request, listener);
        listener.setQuestion(question, false);
        return listener.getAnswer();
    }

    private List<TopicMessage> persistConversation(Long userId, Long topicId, Long platformId, String question, String answer) {
        // 将对话信息持久化到MySQL数据库
        List<RoleContent> roleContents = new ArrayList<>();
        roleContents.add(new RoleContent("user", question));
        roleContents.add(new RoleContent("assistant", answer));
        return topicMessageService.saveMessages(userId, topicId, platformId, roleContents);
    }
}